//
//  BSCommentViewController.m
//  BaiSi
//
//  Created by Sycamore on 16/5/27.
//  Copyright © 2016年 Sycamore. All rights reserved.
//

#import "BSCommentViewController.h"
#import "BSThemeCell.h"
#import "BSThemeCellModel.h"
#import "BSThemeItem.h"
#import <AFNetworking/AFNetworking.h>
#import <MJRefresh/MJRefresh.h>
#import <MJExtension/MJExtension.h>
#import "BSCommentItem.h"
#import "BSUserItem.h"
#import "BSCommentCell.h"
#import "BSCommentHeaderView.h"

@interface BSCommentViewController () <UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *toolBar;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong) AFHTTPSessionManager *manager;
@property (nonatomic,strong) NSArray *hotComments;                 //最热评论
@property (nonatomic,strong) NSMutableArray *latestComments;       //最新评论

@property (nonatomic,strong) NSArray *top_cmt;    //作用：记录cellModel的top_cmt,免得清空后回到上一个控制器后，上一个控制器的top_cmt也清空了
@end

@implementation BSCommentViewController

static NSString * const cellID = @"commentCell";
static NSString * const headerID = @"header";

#pragma mark 懒加载
- (AFHTTPSessionManager *)manager
{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

- (NSMutableArray *)latestComments
{
    if (!_latestComments) {
        _latestComments = [NSMutableArray array];
    }
    return _latestComments;
}


#pragma mark 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //导航条内容
    [self setupNavigation];
    
    //监听键盘位置改变通知
    [self setupToolBar];
    //设置tableView相关
    [self setupTableView];
    
    //设置刷新
    [self setupRefresh];
}


- (void)setupNavigation
{
    self.navigationItem.title = @"评论";
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:[UIImage imageNamed:@"comment_nav_item_share_icon"] highlightedImage:[UIImage imageNamed:@"comment_nav_item_share_icon_click"] target:self action:@selector(shareButtonClick)];
}

- (void)setupToolBar
{
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)setupTableView
{
    _tableView.backgroundColor = BSTintColor;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BSCommentCell class]) bundle:nil] forCellReuseIdentifier:cellID];
    [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BSCommentHeaderView class]) bundle:nil] forHeaderFooterViewReuseIdentifier:headerID];
    
    //self-sizing
    _tableView.estimatedRowHeight = 100;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    
    //确定cell的高度前，需要对视图模型进行处理（过滤最热评论）
    if (_cellModel.item.top_cmt) {
        self.top_cmt = _cellModel.item.top_cmt;      //搞个属性保存起来，回去时再重置
        _cellModel.item.top_cmt = nil;               //清空视图模型里计算的尺寸，cell也就不展示最热评论了
        _cellModel.item.commentItem = nil;           //注意这个也需要清空，不然还会用以前的！
        _cellModel.item = _cellModel.item;           //这句代码很重要，能让cellModel重新计算一遍cell的高度
    }
    
    BSThemeCell *cell = [[BSThemeCell alloc]init];   //该方法内部会调用cell的initWithStyle方法
    cell.cellModel = _cellModel;
    cell.frame = CGRectMake(0, 0, BSScreenWidth, _cellModel.cellHeight);
    
    //尺寸不对，可以将其包装一层View
    UIView *headerView = [[UIView alloc]init];
    headerView.bs_height = cell.bs_height+ BSSmallMargin * 2;    //cell相对于headerView向下移动了10，所以headerView在高度在cell的基础上需要加10
    headerView.backgroundColor = BSTintColor;
    [headerView addSubview:cell];
    
    _tableView.tableHeaderView = headerView;
    
}

- (void)setupRefresh
{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    //开始下啦刷新
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
    //重置视图模型
    if (self.top_cmt) {
        _cellModel.item.top_cmt = self.top_cmt;
        
        //这句代码不能少，返回上一个控制器后再重新计算一遍
        _cellModel.item = _cellModel.item;
    }
    
}

#pragma mark 加载网络数据
- (void)loadNewData
{
    //取消之前的所有任务
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    BSWeakSelf;
    NSDictionary *params = @{
                             @"a" : @"dataList",
                             @"c" : @"comment",
                             @"data_id" : _cellModel.item.ID,
                             @"hot" : @1
                             };
    [self.manager GET:BSBaseURL parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        
        
//        [responseObject writeToFile:@"/Users/Sycamore/Desktop/comment.plist" atomically:YES];
        
        if ([responseObject isKindOfClass:[NSArray class]]) {
            weakSelf.tableView.mj_header.hidden = YES;  //如果返回的是个空数组，直接隐藏上拉刷新，返回
            
            return ;
        }
        
        //最热评论
        _hotComments = [BSCommentItem mj_objectArrayWithKeyValuesArray:responseObject[@"hot"]];
        
        //最新评论
        NSArray *array = [BSCommentItem mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        [weakSelf.latestComments addObjectsFromArray:array];
        
        
        
        [weakSelf.tableView reloadData];
        
        [weakSelf.tableView.mj_header endRefreshing];
        
        //判断是否隐藏footer
        if (weakSelf.latestComments.count >= [responseObject[@"total"] integerValue]) {
            weakSelf.tableView.mj_footer.hidden = YES;
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [weakSelf.tableView.mj_header endRefreshing];

    }];

}

- (void)loadMoreData
{
    //取消之前的所有任务
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    BSWeakSelf;
    NSDictionary *params = @{
                             @"a" : @"dataList",
                             @"c" : @"comment",
                             @"data_id" : _cellModel.item.ID,
                             @"lastcid" : [self.latestComments.lastObject ID]
                             };
    [self.manager GET:BSBaseURL parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        
        if ([responseObject isKindOfClass:[NSArray class]]) {
            
            //提示用户没有更多数据
            weakSelf.tableView.mj_footer.hidden = YES;
            return ;
        }
        //        [responseObject writeToFile:@"/Users/Sycamore/Desktop/comment.plist" atomically:YES];
        
        //最新评论
        NSArray *array = [BSCommentItem mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        [weakSelf.latestComments addObjectsFromArray:array];
        
        
        [weakSelf.tableView reloadData];
        
        //判断是否隐藏footer
        if (weakSelf.latestComments.count >= [responseObject[@"total"] integerValue]) {
            weakSelf.tableView.mj_footer.hidden = YES;
        }
        else{
            [weakSelf.tableView.mj_footer endRefreshing];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [weakSelf.tableView.mj_footer endRefreshing];
    }];

}


#pragma mark 事件监听
- (void)shareButtonClick
{
    BSFunction;
}

//键盘尺寸改变的时候就发出通知，toolBar的位置随之改变
- (void)keyBoardWillChangeFrame:(NSNotification *)noti
{
    NSDictionary *userInfo = noti.userInfo;
    
    //动画间隔
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    //需要偏移的距离
    CGRect  endFrame =  [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat ty = endFrame.origin.y - BSScreenHeight;
    
    [UIView animateWithDuration:duration animations:^{
        
        //让工具条随键盘移动
        _toolBar.transform = CGAffineTransformMakeTranslation(0, ty);
    }];
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_hotComments.count ) {
        return 2;
    }
    if (_latestComments.count) {
        return 1;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 && _hotComments.count) {
        return _hotComments.count;
    }
    return _latestComments.count ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    BSCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    if (indexPath.section == 0 && _hotComments.count) {
        cell.commentItem = _hotComments[indexPath.row];
    }
    else {
        cell.commentItem = _latestComments[indexPath.row];
    }
    
    return cell;
}

//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//    if (section == 0 && _hotComments.count) {
//        return @"最热评论";
//    }
//    return @"最新评论";
//}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    BSCommentHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerID];
    if (section == 0 && _hotComments.count) {
        
        header.text = @"最热评论";
    }
    else {
        header.text = @"最新评论";
    }

    UIView *backgroundView = [[UIView alloc]init];
    backgroundView.backgroundColor = BSTintColor;
    header.backgroundView = backgroundView;

    return header;
}








@end
